import Icon from '@/components/Icon';
import NavBar from '@/components/Navbar';
import { useAppSelector } from '@/store';
import {
  clearHistoriesAction,
  clearSuggestsAction,
  getSuggestsAction,
  saveHistoriesAction,
} from '@/store/action/search';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';
import DOMPurify from 'dompurify';
import { Toast } from 'antd-mobile';
import { removeLocalHistories, setLocalHistories } from '@/utils/storage';
import { useHistory } from 'react-router-dom';

const highlight = (keyword: string, item: string) => {
  const reg = new RegExp(`(${keyword})`, 'gi');
  return item.replace(reg, `<span>$1</span>`);
};
export default function Search() {
  const history = useHistory();
  const timerIdRef = useRef(-1);
  // 需求：防抖，停止按键盘后0.5后触发console
  // 2. 💥每次改变都清除定时器
  const dispatch = useDispatch();

  // 4. 改造受控组件
  const [keyword, setKeyword] = useState('');
  // 2. keyword为空时，清除搜索建议
  useEffect(() => {
    if (!keyword) {
      dispatch(clearSuggestsAction());
    }
  }, [keyword, dispatch]);
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setKeyword(e.target.value);

    clearTimeout(timerIdRef.current);
    if (!e.target.value.trim()) return;
    // 1. 开启定时器
    timerIdRef.current = window.setTimeout(() => {
      // 3.dispatch
      dispatch(getSuggestsAction(e.target.value));
    }, 500);
  };

  const handleSearch = () => {
    if (!keyword.trim()) return Toast.show({ content: '搜索内容不能为空' });
    handlegotoresult(keyword);
    dispatch(saveHistoriesAction(keyword));
  };
  // 3. 记得卸载时，清除定时器
  useEffect(() => {
    return () => {
      clearTimeout(timerIdRef.current);
      dispatch(clearSuggestsAction());
    };
  }, [dispatch]);
  const handleclear = () => {
    dispatch(clearSuggestsAction());
    setKeyword('');
  };
  const { suggestList, histories } = useAppSelector((state) => state.search);
  const tenHistories = histories.slice(0, 10);
  // 2. 监听histories的变化，缓存记录
  useEffect(() => {
    setLocalHistories(histories);
  }, [histories]);
  const handleclearhistories = () => {
    dispatch(clearHistoriesAction());
    removeLocalHistories();
  };
  const handlegotoresult = (key: string) => {
    history.push('/search/result?q=' + key);
  };
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        right={
          <span className="search-text" onClick={handleSearch}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input
              type="text"
              value={keyword}
              placeholder="请输入关键字搜索"
              onChange={(e) => handleChange(e)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
            />

            {/* 清空输入框按钮 */}
            {keyword.trim() && (
              <Icon
                type="iconbtn_tag_close"
                className="icon-close"
                onClick={handleclear}
              />
            )}
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      {!keyword.trim() && !!histories.length && (
        <div className="history" style={{ display: 'block' }}>
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={handleclearhistories}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {tenHistories.map((item) => {
              return (
                <span
                  className="history-item"
                  key={item}
                  onClick={() => handlegotoresult(item)}
                >
                  {item}
                  <span className="divider"></span>
                </span>
              );
            })}
          </div>
        </div>
      )}

      {/* 搜素建议结果列表 */}
      {keyword.trim() && (
        <div className="search-result">
          {suggestList.map((item, index) => {
            return (
              <div
                className="result-item"
                key={index}
                onClick={() => handlegotoresult(item)}
              >
                <Icon className="icon-search" type="iconbtn_search" />
                <div
                  className="result-value"
                  dangerouslySetInnerHTML={{
                    __html: DOMPurify.sanitize(highlight(keyword, item)),
                  }}
                ></div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
